import random

import soundfile as sf
import matplotlib.pyplot as plt
import time
import os
import musicpy as mp

from dataset import get_files, load_audio_as_spec
from simpledaw import SimpleDAW

preset_dir = r"B:\muse_repo\Presets\_Legacy"
midi_dir = r"F:\编曲资源"
output_dir = r"C:\dev_spa\DMuse\202202b6"


if not os.path.exists(output_dir):
    os.mkdir(output_dir)
    os.mkdir(output_dir + '\\x1')
    os.mkdir(output_dir + '\\x2')

fxp_files = get_files(preset_dir, 'fxp')
mid_files = get_files(midi_dir, 'mid')


simple_daw = SimpleDAW(plugin='C:/VST/64bit/Sylenth1.dll', sample_rate=44100, bpm=120)

counter = 0
with open(output_dir + '\\' + 'labels.txt', 'wt') as file:
    it = iter(fxp_files)
    for i in range(2000):
        if random.uniform(0, 1) < 0.5:
            fxp1 = it.__next__()
            fxp2 = fxp1
        else:
            fxp1 = it.__next__()
            fxp2 = it.__next__()
        
        simple_daw.load_midi(random.choice(mid_files))
            
        simple_daw.load_preset(fxp1)
        audio1 = simple_daw.render(2.)
        output_filename = output_dir + '\\x1\\' + str(counter) + '.wav'
        sf.write(output_filename, audio1, samplerate=44100)
        
        simple_daw.load_preset(fxp2)
        audio2 = simple_daw.render(2.)
        output_filename = output_dir + '\\x2\\' + str(counter) + '.wav'
        sf.write(output_filename, audio2, samplerate=44100)
        
        counter += 1
        file.write('{}\n'.format(1 if fxp1 == fxp2 else 0))

        # spec = load_audio_as_spec(output_filename, (224, 224), 100.)
        # plt.imshow(spec[..., 0])
        # plt.show()
        # time.sleep(1)

